<?php

namespace App\Services;


use App\Exceptions\ServiceException;
use App\Models\Book;
use App\Models\BookChapter;
use App\Models\MemberPrices;
use App\Models\Orders;
use App\Models\Users;
use App\User;
use App\Utils\ArrayUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;

/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/10/30
 * Time: 4:12 PM
 */
class OrderService
{

    /**
     * 支付成功
     * @param $orderCode
     * @param $thirtyOrder
     * @param array $log
     * @return \App\Models\Orders
     * @throws \App\Exceptions\ServiceException
     * @throws \Exception
     */
    public static function pay($orderCode, $thirtyOrder, $log = [])
    {
        /** @var Orders $order */
        $order = Orders::where(['order_code' => $orderCode])->first();
        if (empty($order)){
            throw new ServiceException('订单不存在');
        }
        if ($order->status != Orders::STATUS_INIT){
            return $order;
        }

        /** @var Users $user */
        $user = Users::find($order->user_id);

        if ($order->goods_type == Orders::GOODS_TYPE_MEMBER){
            /** @var MemberPrices $memberPrice */
            $memberPrice = MemberPrices::find($order->goods_id);
            if ($memberPrice->type == MemberPrices::TYPE_ONE_YEAR){
                //增加一年会员时间
                if (time() > $user->expire_time){
                    $user->expire_time = time() + 60 * 60 * 24 * 365;
                }else{
                    $user->expire_time = $user->expire_time + 60 * 60 * 24 * 365;
                }
            }

            //其他会员时间待定
        }


        try{
            DB::beginTransaction();

            $order->status = Orders::STATUS_SUCCESS;
            $order->thirty_order = $thirtyOrder;
            $order->logs = json_encode($log);
            $order->pay_time = time();

            if (!$order->save()){
                throw new ServiceException('订单 保存失败');
            }

            $user->save();

            DB::commit();

            return $order;
        }catch(\Exception $e){
            Log::error(__METHOD__ . $e->getMessage());
            DB::rollBack();

            throw $e;
        }

    }

    /**
     * 创建订单
     * @param \App\User $user
     * @param $goodsType
     * @param $goodsId
     * @param $bookId
     * @return mixed
     * @throws \App\Exceptions\ServiceException
     */
    public static function create(User $user, $goodsType, $goodsId, $bookId, $payType = Orders::PAY_TYPE_MINI_WX)
    {

        $order = new Orders();
        $order->user_id = $user->id;
        $order->status = Orders::STATUS_INIT;
        $order->order_code = Orders::getOrderCode();
        $order->goods_type = $goodsType;
        $order->goods_id = $goodsId;
        $order->pay_type = $payType;
        $order->book_id = $bookId;
        $order->date = date('Y-m-d');

        if (in_array($goodsType, [Orders::GOODS_TYPE_BOOK, Orders::GOODS_TYPE_BOOK_CHAPTER])){
            $exists = Orders::where([
                'user_id' => $user->id,
                'status' => Orders::STATUS_SUCCESS,
                'goods_type' => $goodsType,
                'goods_id' => $goodsId,
            ])->first();
            if (!empty($exists)){
                throw new ServiceException('已购买该商品');
            }
        }


        if ($goodsType == Orders::GOODS_TYPE_BOOK){
            /** @var \App\Models\Book $book */
            $book = Book::find($goodsId);
            if (empty($book)){
                throw new ServiceException('商品不存在');
            }

            $order->price = self::bookPrice($user->id, $book)['price'];

            $order->title = "购买书籍《{$book->name}》";
        }elseif ($goodsType == Orders::GOODS_TYPE_BOOK_CHAPTER){
            /** @var BookChapter $bookChapter */
            $bookChapter = BookChapter::find($goodsId);
            if (empty($bookChapter)){
                throw new ServiceException('商品不存在');
            }
            $order->price = $bookChapter->price;

            $order->title = "购买书籍章节《{$bookChapter->name}》";

        }elseif ($goodsType == Orders::GOODS_TYPE_MEMBER){
            /** @var MemberPrices $memberPrice */
            $memberPrice = MemberPrices::find($goodsId);
            if (empty($memberPrice)){
                throw new ServiceException('商品不存在');
            }
            $order->price = $memberPrice->current_price;
            $order->title = "购买大会员";
        }
        if ($order->price <= 0){
            throw new ServiceException('免费产品，无需支付');
        }

        try{
            if (!$order->save()){
                throw new ServiceException('服务器繁忙');
            }

            return Orders::find($order->id);
        }catch(\Exception $e){
            Log::error(__METHOD__ . $e->getMessage());
            throw $e;
        }

    }

    public static function bookPrice($userId, $bookId)
    {
        /** @var Book $book */
        $book = Book::find($bookId);
        if (empty($book)){
            return null;
        }

        $chapters = $book->chapters;

        //已经购买的章节ID
        $buyChapterIds = Orders::where([
            'user_id' => $userId,
            'status' => Orders::STATUS_SUCCESS,
            'goods_type' => Orders::GOODS_TYPE_BOOK_CHAPTER,
        ])->pluck('goods_id')->toArray();

        //付费的章节ID
        $payChapterCt = 0;//购买的章节数
        $payChapterOriginPrice = 0;//购买章节原价

        /** @var BookChapter $chapter */
        foreach($chapters as $chapter){
            if ($chapter->is_free == 0 && !in_array($chapter->id, $buyChapterIds)){
                //付费章节
                $payChapterCt++;
                $payChapterOriginPrice = $payChapterOriginPrice + $chapter->price;
            }

        }

        $book = [
            'id' => $book->id,
            'origin_price' => $payChapterOriginPrice,
            'price' => ceil($payChapterOriginPrice * ($book->rate / 100)),
            'rate' => $book->rate,
            'chapter_ct' => $payChapterCt
        ];

        return $book;

    }

}
